<template>
	<div class="header-content" :style="{ backgroundColor: bgColor }">
		<div class="logo" @click="goHome">
			<img :src="store.siteLogo" alt="" />
			<span class="site-name">{{ store.siteName }}</span>
		</div>
		<div class="header-right">
			<div class="top">
				<Locale />
				<div :class="['top-right', isLoggedIn ? 'top-right--user' : 'top-right--guest']">
					<template v-if="isLoggedIn">
						<el-dropdown class="user-dropdown" trigger="click">
							<div class="user-entry">
								<el-avatar shape="circle" :size="36" :src="userAvatar" />
								<span class="user-name">{{ displayName }}</span>
								<el-icon class="user-caret">
									<ArrowDown />
								</el-icon>
							</div>
							<template #dropdown>
								<el-dropdown-menu class="user-menu">
									<el-dropdown-item @click="goProfile">
										{{ t('webBar.profile') }}
									</el-dropdown-item>
									<el-dropdown-item divided @click="handleLogout">
										{{ t('webBar.logout') }}
									</el-dropdown-item>
								</el-dropdown-menu>
							</template>
						</el-dropdown>
					</template>
					<template v-else>
						<div class="login" @click="handleLogin">
							<div class="skew-content">{{ t('webBar.login') }}</div>
						</div>
						<div class="member-signup" @click="handleSignup">
							<div class="skew-content">{{ t('webBar.signup') }}</div>
						</div>
					</template>
				</div>
			</div>
			<div class="bottom">
				<nav class="nav-bar">
					<template v-for="(item, index) in visibleMenuItems" :key="index">
						<div data-aos="fade-right" :data-aos-delay="index * 100">
							<div class="nav-item" :class="{ 'is-active': activeMenu == item.id }" @click="handleNavClick(item)">
								<span class="nav-item-title">{{ item.name }}</span>
								<ul v-if="item.children?.length" class="sub-nav-bar">
									<li class="sub-nav-item" v-for="sItem in item.children" :class="{ active: activeMenu == sItem.id }"
										@click.stop="handleNavClick(sItem)">
										<span class="sub-nav-item-title">{{ sItem.name }}</span>
									</li>
								</ul>
							</div>
						</div>
					</template>
					<div class="nav-more" :class="{ 'is-active': isMoreMenuActive }" v-if="hiddenMenuItems.length > 0">
						<div data-aos="fade-right" :data-aos-delay="(visibleMenuItems.length - 1) * 100">
							<div class="more-title">
								<!-- {{ t('webBar.more') }} -->
								<span class="more-icon">
									<span class="more-icon__line"></span>
									<span class="more-icon__line"></span>
									<span class="more-icon__line"></span>
								</span>
							</div>
							<div class="more-dropdown">
								<div v-for="(item, index) in hiddenMenuItems" :key="index" class="dropdown-item" :class="{
									'is-active': activeMenu == item.id,
								}" @click="handleNavClick(item)">
									<span>
										{{ item.name }}
									</span>
								</div>
							</div>
						</div>
					</div>
				</nav>
			</div>
		</div>
	</div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ArrowDown } from '@element-plus/icons-vue';
import { isCnLocale } from '~/utils/utils';

const { t, locale } = useI18n();
const props = defineProps({
	bgColor: {
		type: String,
		default: '#000000',
	},
	menuList: {
		type: Array,
		default: [],
	},
	webSiteInfo: {
		type: Object,
		default: {},
	},
});

const route = useRoute();
const { $navigate } = useNuxtApp();
const store = useStore.appStore();
const userStore = useStore.userStore();
const tokenCookie = useCookie('token');

const isLoggedIn = computed(() => {
	return !!(userStore.token || tokenCookie.value);
});

const userProfile = computed(() => userStore.profile);

const userAvatar = computed(() => {
	return userProfile.value?.avatar || userStore.user?.avatar || '/favicon.ico';
});

const displayName = computed(() => {
	return (
		userProfile.value?.nickname ||
		userProfile.value?.username ||
		userStore.user?.username ||
		userStore.user?.email ||
		''
	);
});

watch(
	() => isLoggedIn.value,
	val => {
		if (val && !userProfile.value) {
			userStore.getUserInfoAction();
		}
	},
	{ immediate: true }
);

// 根据当前路由路径计算激活的菜单项
const activeMenu = computed(() => {
	let currentPath = route.path;

	// 如果不是默认语言（zh-HK），需要移除语言前缀
	if (!isCnLocale(locale.value)) {
		const idx = currentPath.indexOf('/', 2);
		if (idx !== -1) {
			currentPath = currentPath.substring(idx);
		}
	}

	const sortedMenuItems = [...allMenuItems.value].sort((a, b) => {
		const aPathLength = (a.path || '').length;
		const bPathLength = (b.path || '').length;
		return bPathLength - aPathLength; // 降序排列，长的在前
	});
	// 查找匹配的菜单项
	const matchedMenu = sortedMenuItems.find(item => {
		if (!item.path) return false;
		if (item.path.trim() === currentPath) {
			return true;
		}
		if (currentPath.startsWith(item.path + '/')) {
			if (item.path == '/web' && currentPath !== '/web') {
				return false;
			}
			return true;
		}
		return false;
	});
	return matchedMenu ? matchedMenu.id : null;
});

// 登录
const handleLogin = () => {
	$navigate('/login');
};

const handleSignup = () => {
	$navigate('/login/enroll');
};

const goHome = () => {
	$navigate('/web');
};

const goProfile = () => {
	$navigate('/admin/courseSystem/courseOfMy');
};

const handleLogout = async () => {
	await userStore.logoutAction();
	$navigate('/web');
};
// 定义所有菜单项
const allMenuItems = ref([]);

// 计算可见菜单项和隐藏菜单项
const visibleMenuItems = ref([]);
const hiddenMenuItems = ref([]);

// 添加计算属性判断更多菜单是否激活
const isMoreMenuActive = computed(() => {
	return hiddenMenuItems.value.some(item => activeMenu.value === item.id);
});

function convertToTree(flatData, rootParentId = 0) {
	const nodeMap = new Map();
	flatData.forEach(node => {
		nodeMap.set(node.id, { ...node, children: [] });
	});
	const tree = [];
	flatData.forEach(node => {
		const currentNode = nodeMap.get(node.id);
		const parentNode = nodeMap.get(node.parentId);
		if (node.parentId === rootParentId) {
			tree.push(currentNode);
		} else if (parentNode) {
			parentNode.children.push(currentNode);
		}
	});

	return tree;
}

watch(
	() => props.menuList,
	newVal => {
		const treeData = convertToTree(newVal.sort((a, b) => a.sort - b.sort));
		allMenuItems.value = treeData;
		nextTick(() => {
			updateMenuItems();
		});
	}
);
// 监听窗口大小变化
onMounted(() => {
	window.addEventListener('resize', updateMenuItems);
});

onUnmounted(() => {
	window.removeEventListener('resize', updateMenuItems);
});

// 更新菜单项显示状态
const updateMenuItems = () => {
	const menuContainer = document.querySelector('.nav-bar');
	if (!menuContainer) return;
	const containerWidth = menuContainer.offsetWidth;
	const moreButtonWidth = 100; // 更多按钮的预估宽度
	const itemWidth = 120; // 每个菜单项的预估宽度
	const maxVisibleItems = Math.max(0, Math.floor((containerWidth - moreButtonWidth) / itemWidth));
	visibleMenuItems.value = allMenuItems.value.slice(0, maxVisibleItems);
	hiddenMenuItems.value = allMenuItems.value.slice(maxVisibleItems);
};

const handleNavClick = item => {
	$navigate(`${item.path.trim()}?pageName=${item.name}&id=${item.id}`);
};
</script>

<style lang="less" scoped>
.header-content {
	width: 100%;
	min-width: 320px;
	height: 140px;
	// box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.25);
	border-radius: 0px 0px 0px 0px;
	display: flex;
	position: fixed;
	top: 0;
	left: 0;
	z-index: 1000;

	.logo {
		display: flex;
		align-items: center;
		gap: 16px;
		padding: 0px 0 0 80px;
		flex-shrink: 0;
		cursor: pointer;

		height: 70px;

		img {
			width: 100px;
			// height: 100%;
			// border-radius: 50%;
		}

		.site-name {
			font-size: 24px;
			font-weight: bold;
			color: #ffffff;
			white-space: nowrap;
			transition: color 0.2s;
		}

	}

	.header-right {
		flex: 1;

		.top {
			width: 100%;
			height: 80px;
			display: flex;
			flex-direction: row;
			justify-content: flex-end;
			align-items: center;

			.top-right {
				display: flex;
				height: 100%;
			}

			.top-right--guest {
				align-items: center;
				gap: 0;
				margin-left: 0;
			}

			.top-right--user {
				align-items: center;
				gap: 24px;
				margin-left: 40px;
			}

			.login {
				margin-left: 50px;
			}

			.login,
			.member-signup {
				min-width: 192px;
				box-sizing: border-box;
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 20px;
				font-weight: bold;
				color: #ffffff;
				cursor: pointer;
				white-space: nowrap;
				padding: 0 40px;
			}

			.login {
				background-color: var(--el-color-primary-dark-8, #0f3460);
				transform: skewX(-10deg);
				margin-right: -20px;
				position: relative;
				z-index: 2;

				// .skew-content {
				// 	transform: skewX(10deg);
				// }

				&:hover {
					color: var(--el-color-primary);
				}
			}

			.member-signup {
				position: relative;
				z-index: 1;

				// .skew-content {
				// 	transform: skewX(0deg);
				// }
			}

			.member-signup::before {
				content: '';
				position: absolute;
				top: 0;
				left: -40px;
				right: 0;
				bottom: 0;
				background: var(--theme-gradient-bg);
				box-shadow: 0px 10px 15px 0px rgba(1, 115, 153, 0.2);
				z-index: -1;
			}

			.user-dropdown {
				:deep(.el-tooltip__trigger) {
					display: flex;
					align-items: center;
				}
			}

			.user-entry {
				display: flex;
				align-items: center;
				gap: 12px;
				color: #ffffff;
				cursor: pointer;
				padding: 10px 14px;
				border-radius: 8px;
				transition: background-color 0.2s ease;

				.user-name {
					font-weight: 700;
					font-size: 18px;
					white-space: nowrap;
				}

				.user-caret {
					color: #ffffff;
					font-size: 16px;
				}

				&:hover {
					background: rgba(255, 255, 255, 0.08);
				}
			}

			.user-menu {
				min-width: 200px;
				background: rgba(0, 0, 0, 0.9);
				border: 1px solid rgba(255, 255, 255, 0.08);
				backdrop-filter: blur(4px);

				:deep(.el-dropdown-menu__item) {
					color: rgba(255, 255, 255, 0.92);
					font-size: 16px;

					&:hover {
						background: rgba(255, 255, 255, 0.06);
						color: var(--el-color-primary);
					}
				}

				:deep(.el-dropdown-menu__item--divided) {
					border-top-color: rgba(255, 255, 255, 0.08);
				}
			}
		}

		.bottom {
			width: 100%;
			height: 60px;
			box-sizing: border-box;
			padding-right: 102px;

			.nav-bar {
				width: 100%;
				display: flex;
				justify-content: flex-end;
				align-items: center;

				.nav-item {
					padding: 0;
					margin: 0 30px;
					text-align: center;
					position: relative;
					cursor: pointer;
					height: 60px;

					background: transparent;
					border: none;
					transition: color 0.2s;
					white-space: nowrap;

					&.is-active {
						background: transparent;

						.nav-item-title {
							color: var(--el-color-primary);
						}
					}

					.nav-item-title {
						font-weight: bold;
						line-height: 60px;
						color: #fff;
						font-size: 18px;
					}

					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 0;
						width: 0;
						height: 2px;
						background: var(--theme-gradient-bg);
						transition: width 0.3s ease;
					}

					&:hover::after,
					&.is-active::after {
						width: 100%;
					}

					&:hover .sub-nav-bar {
						transform: scaleY(1) translateX(-50%);
					}
				}

				.sub-nav-bar {
					position: absolute;
					top: 68px;
					left: 50%;
					transform: scaleY(0) translateX(-50%);
					transform-origin: top;
					transition: transform 0.2s linear .1s;
					background-color: rgba(0, 0, 0, 0.7);
					width: 220px;
					list-style: none;
					margin: 0;
					padding: 0;
				}

				.sub-nav-item {
					user-select: none;
					overflow: hidden;
					text-overflow: ellipsis;
					padding: 15px 12px;
					color: rgba(255, 255, 255, 0.8);

					&-title {
						font-weight: 400;
						font-size: 18px;
					}

					&.active,
					&:hover {
						color: var(--el-color-primary);
					}

					&+.sub-nav-item {
						border-top: 1px solid rgba(255, 255, 255, 0.1);
					}
				}

				.nav-more {
					position: relative;

					.more-title {
						margin: 0 30px;
						text-align: center;
						position: relative;
						cursor: pointer;
						color: #fff;
						padding: 20px 0;
						background: transparent;
						border: none;
						transition: color 0.2s;
						white-space: nowrap;

						.more-icon {
							display: flex;
							flex-direction: column;
							width: 26px;
							height: 20px;
							justify-content: space-between;

							&__line {
								display: block;
								width: 100%;
								height: 2px;
								background-color: currentColor;
								transition: width 0.2s;

								&:nth-child(2) {
									width: 75%;
								}

								&:nth-child(3) {
									width: 50%;
								}
							}
						}
					}

					&.is-active,
					&:hover {
						.more-title {
							color: var(--el-color-primary);

							.more-icon .more-icon__line {
								width: 100% !important;
							}
						}
					}

					&:hover .more-dropdown {
						transform: scaleY(1);
					}

					.more-dropdown {
						position: absolute;
						top: 68px;
						right: 0;
						min-width: 220px;
						background-color: rgba(0, 0, 0, 0.7);
						box-sizing: border-box;
						padding: 10px 0;
						z-index: 10;
						transform: scaleY(0);
						transform-origin: top;
						transition: transform 0.2s linear .1s;

						.dropdown-item {
							padding: 10px 30px;
							box-sizing: border-box;
							text-align: center;
							cursor: pointer;
							font-weight: 400;
							font-size: 18px;
							white-space: nowrap;
							color: rgba(255, 255, 255, 0.8);

							&:hover {
								color: var(--el-color-primary);
							}

							&.is-active {
								color: var(--el-color-primary);
								font-weight: bold;
							}
						}
					}
				}
			}
		}
	}
}
</style>
